<template>
  <div class="page praticle-page flex-col">
    <div class="box_1 flex-row">
      <div class="group_1 ">
        <img class="label_4" src="@/assets/ide/liebiao.png" />
        <span>{{ examTitle ? examTitle : 精选题库 }}</span>
        <el-countdown v-if="examEndTime && new Date() < new Date(examEndTime)" class="exam-time-countdown"
          @finish="handleCountdownFinish" title="距离竞赛结束还有:" :value="new Date(examEndTime)" />
      </div>
      <div class="group_2">
        <!-- 提交当前题目代码按钮 -->
        <el-button type="primary" plain @click="submitQuestion">提交代码</el-button>

        <!-- 提交整个竞赛按钮（只在竞赛模式下显示） -->
        <el-button v-if="examId && examEndTime && new Date() < new Date(examEndTime)" type="warning" plain
          @click="confirmSubmitAll">
          提交竞赛
        </el-button>

        <!-- 提交竞赛确认对话框 -->
        <el-dialog v-model="showSubmitAllDialog" title="提交竞赛确认" width="30%">
          <span>您确定要提交整个竞赛吗？请确认：</span>
          <ul class="submit-confirm-list">
            <li>✓ 已完成所有题目</li>
            <li>✓ 已检查所有代码</li>
            <li>✓ 提交后无法修改</li>
          </ul>
          <template #footer>
            <el-button @click="showSubmitAllDialog = false">取消</el-button>
            <el-button type="primary" @click="submitAllQuestions">确认提交</el-button>
          </template>
        </el-dialog>
      </div>
      <span class="ide-back" @click="goBack()">返回</span>
    </div>
    <div class="box_8 flex-col">
      <div class="group_12 flex-row justify-between">
        <div class="image-wrapper_1 flex-row">
          <img class="thumbnail_2" src="@/assets/ide/xiaobiaoti.png" />
          <div class="question-nav">
            <span>题目描述</span>
          </div>
          <div class="question-nav" @click="preQuestion">
            <el-icon>
              <span>上一题</span>
              <ArrowLeft />
            </el-icon>
          </div>
          <div class="question-nav" @click="nextQuestion">
            <el-icon>
              <ArrowRight />
              <span>下一题</span>
            </el-icon>
          </div>
        </div>
        <div class="image-wrapper_2 flex-row">
          <img class="image_1" src="@/assets/ide/daima.png" />
          代码
        </div>
      </div>
      <div class="group_13 flex-row justify-between">
        <div class="box_3 flex-col">
          <span class="question-title">{{ questionDetail.title }}</span>
          <span class="question-limit">
            <div v-if="questionDetail.difficulty === 1">题目难度：简单 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 2">题目难度：中等 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
            <div v-if="questionDetail.difficulty === 3">题目难度：困难 时间限制：{{ questionDetail.timeLimit }} ms 空间限制：{{
              questionDetail.spaceLimit }} 字节</div>
          </span>
          <span class="question-content" v-html="questionDetail.content"></span>
        </div>
        <div class="group_14 flex-col">
          <div class="group_8 flex-col">
            <codeEditor ref="defaultCodeRef" @update:value="handleEditorContent">
            </codeEditor>
          </div>
          <div class="results">
            <div class="code-result flex-row">
              <div class="top" style="display: flex; ">
                <img class="code-result-image" src="@/assets/ide/codeResult.png"  />
                <span class="code-result-content" style="margin-left: 10px;">执行结果</span>
                <div class="text-wrapper_2 flex-row justify-between" style="margin-left: 20px;">
                  <span class="text_1 red" style="color: red;" v-if="userQuestionResultVO.pass === 0">未通过</span>
                  <span class="text_1 success" style="color: green;" v-if="userQuestionResultVO.pass === 1">通过</span>
                  <span class="text_1 warning" style="color: red;" v-if="userQuestionResultVO.pass === 2">请先执行代码</span>
                  <span class="text_1 info" v-if="userQuestionResultVO.pass === 3">系统正在处理您的代码，请稍后</span>
                </div>
              </div>
              <div class="group_15 flex-row">
                <div class="section_1 flex-row">
                  <div class="section_3 flex-col">
                    <span class="error-text" v-if="userQuestionResultVO.pass === 0">异常信息：{{
                      userQuestionResultVO.exeMessage }}</span>
                    <el-table
                      v-else="userQuestionResultVO.userExeResultList && userQuestionResultVO.userExeResultList.length > 0"
                      :data="userQuestionResultVO.userExeResultList">
                      <el-table-column prop="input" label="输入" />
                      <el-table-column prop="output" label="预期结果" />
                      <el-table-column prop="exeOutput" label="实际输出" />
                    </el-table>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue"
import codeEditor from "@/components/CodeEditor.vue"
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { useRoute } from "vue-router"
import { getQuestionDetailService, preQuestionService, nextQuestionService, getQuestionResultService } from "@/apis/question"
import router from "@/router"
import { examNextQuestionService, examPreQuestionService, getExamFirstQuestionService } from "@/apis/exam"
import { ElMessage } from "element-plus"
import { userSubmitService, userSubmitExamService } from "@/apis/user"

function goBack() {
  router.go(-1);
}
const questionDetail = reactive({})
const defaultCodeRef = ref()

let questionId = useRoute().query.questionId
let examId = useRoute().query.examId
let examTitle = useRoute().query.examTitle
let examEndTime = useRoute().query.examEndTime

console.log('examTitle: ', examTitle)

async function getQuestionDetail() {
  if (examId && (questionId == null || questionId == '')) {
    const eqrs = await getExamFirstQuestionService(examId);

    // 判断用户是否已经提交过竞赛
    if (eqrs.data === "用户已经提交过竞赛") {
      alert("您已参加过竞赛！");
      window.location.href = "/c-oj/home/exam"; // 返回到竞赛列表页面
      return; // 结束函数执行
    }

    questionId = eqrs.data;
    console.log('qId: ', questionId);
  }

  const res = await getQuestionDetailService(questionId);
  Object.assign(questionDetail, res.data);
  defaultCodeRef.value.setAceCode(questionDetail.defaultCode);
}
getQuestionDetail()

async function preQuestion() {
  if (examId) {
    //竞赛中上一题的逻辑  需要提供一个竞赛中获取上一题的接口
    const res = await examPreQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await preQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

async function nextQuestion() {
  if (examId) {
    //竞赛中下一题的逻辑 需要提供一个竞赛中获取下一题的接口
    const res = await examNextQuestionService(examId, questionId)
    questionId = res.data
  } else {
    const res = await nextQuestionService(questionId)
    questionId = res.data
  }
  getQuestionDetail()
}

function handleCountdownFinish() {
  ElMessage.info('竞赛已经结束了哦')
  router.push('/c-oj/home/exam')
}

const submitDTO = reactive({
  examId: '',
  questionId: '',
  programType: 0,
  userCode: ''
})

function handleEditorContent(content) {
  submitDTO.userCode = content
}

const userQuestionResultVO = ref({
  pass: 2,  //默认值为2，未提交代码
  exeMessage: '',
  userExeResultList: [],
})

const pollingInterval = ref(null);
let currentTime

function startPolling() {
  stopPolling(); // 停止之前的轮询
  pollingInterval.value = setInterval(() => {
    getQuestionResult();
  }, 2000); // 每隔2秒请求一次
}

function stopPolling() {
  if (pollingInterval.value) {
    clearInterval(pollingInterval.value);
    pollingInterval.value = null;
  }
}
// 新增的状态
const showSubmitAllDialog = ref(false)

// 确认提交整个竞赛
const confirmSubmitAll = () => {
  showSubmitAllDialog.value = true
}

// 提交整个竞赛（纯前端操作）
const submitAllQuestions = () => {

  ElMessage.success('竞赛提交成功！即将返回竞赛列表...')
  const examData = {
    examId: examId.toString() // 将 examId 转换为字符串
  };
  showSubmitAllDialog.value = false
  userSubmitExamService(examData);
  // 3秒后跳转回竞赛列表


  setTimeout(() => {
    router.push('/c-oj/home/exam')
  }, 3000)
}
async function submitQuestion() {
  submitDTO.examId = examId
  submitDTO.questionId = questionId
  await userSubmitService(submitDTO)
  currentTime = new Date().toLocaleString();
  userQuestionResultVO.value.pass = 3
  startPolling()
}

async function getQuestionResult() {
  const res = await getQuestionResultService(submitDTO.examId, submitDTO.questionId, currentTime)
  userQuestionResultVO.value = res.data
  if (userQuestionResultVO.value.pass !== 3) {
    stopPolling();
  }
  console.log('=======userQuestionResultVO', userQuestionResultVO)
}

</script>

<style lang="scss" scoped>
.praticle-page {
  background: #f8fafc;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .box_1 {
    background: linear-gradient(135deg, #2c3e50, #3498db);
    height: 64px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding: 0 24px;
    color: white;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group_1 {
      display: flex;
      align-items: center;
      gap: 16px;

      img {
        filter: invert(1);
        width: 26px;
        height: 26px;
      }

      span {
        font-size: 18px;
        font-weight: 500;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      ::v-deep .exam-time-countdown {
        .el-stat__content {
          font-size: 16px;
          color: #ffd04b !important;
        }
      }
    }

    .ide-back {
      cursor: pointer;
      padding: 8px 16px;
      border-radius: 4px;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      gap: 8px;

      &:hover {
        background: rgba(255, 255, 255, 0.1);
        transform: translateX(-4px);
      }
    }
  }

  .box_8 {
    flex: 1;
    padding: 24px;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .group_12 {
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      padding: 0 24px;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .image-wrapper_1 {
        display: flex;
        align-items: center;
        gap: 32px;

        .question-nav {
          padding: 8px 16px;
          border-radius: 6px;
          transition: all 0.3s;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 8px;
          color: #606266;
          position: relative;

          &:hover {
            background: #f0f4ff;
            color: #409eff;

            &::after {
              content: "";
              position: absolute;
              bottom: -8px;
              left: 50%;
              transform: translateX(-50%);
              width: 60%;
              height: 2px;
              background: #409eff;
            }
          }

          .el-icon {
            font-size: 16px;
          }
        }
      }

      .image-wrapper_2 {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #409eff;
        font-weight: 500;
        position: relative;

        &::before {
          content: "✍️ 代码编辑区";
          position: absolute;
          top: -32px;
          right: 0;
          background: #e8f4ff;
          padding: 4px 12px;
          border-radius: 4px;
          font-size: 12px;
          color: #409eff;
        }

        .image_1 {
          width: 21px;
          height: 16px;
        }
      }
    }

    .group_13 {
      flex: 1;
      margin-top: 16px;
      display: flex;
      gap: 24px;
      min-height: 0;

      /* 关键修复 */
      .results {
        height: 20vh;
        display: flex;
        flex-direction: column;
        margin-top: -30px;
      }

      .box_3 {
        background: white;
        border-radius: 8px;
        padding: 24px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
        overflow-y: auto;
        width: 600px;
        position: relative;



        .question-title {
          font-size: 24px;
          color: #303133;
          margin-bottom: 12px;
          font-weight: 600;
          display: flex;
          align-items: center;
          gap: 12px;

          &::before {
            content: "📌";
            font-size: 1.2em;
          }
        }

        .question-limit {
          background: #f6f8fa;
          padding: 12px 16px;
          border-radius: 8px;
          margin-bottom: 24px;
          font-size: 14px;
          color: #606266;
          line-height: 1.6;
          border-left: 4px solid #409eff;

          &::before {
            content: "⏳ 限制条件";
            display: block;
            font-weight: 500;
            margin-bottom: 8px;
            color: #409eff;
          }
        }

        .question-content {
          font-size: 16px;
          line-height: 1.8;
          color: #606266;

          :deep(pre) {
            background: #f6f8fa;
            padding: 16px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 12px 0;
            font-family: Monaco, Consolas, monospace;
            position: relative;

            &::before {
              position: absolute;
              top: -10px;
              left: 16px;
              background: #e8f4ff;
              padding: 2px 8px;
              border-radius: 4px;
              font-size: 12px;
              color: #409eff;
            }
          }
        }
      }

      .group_14 {
        flex: 1;
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
        overflow: hidden;
        display: flex;
        flex-direction: column;
        min-height: 600px; // 确保最小高度

        .group_8 {
          flex: 1;
          min-height: 300px;
          position: relative;

          &::before {
            content: "🚀 输入你的代码（支持Java/Python/C++）";
            position: absolute;
            top: 12px;
            right: 12px;
            z-index: 1;
            background: rgba(255, 255, 255, 0.9);
            padding: 4px 12px;
            border-radius: 4px;
            font-size: 12px;
            color: #666;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
          }
        }

        .code-result {
          z-index: 10;
          background: #f6f8fa;
          height: 56px;
          display: flex;
          flex-direction: column;

          gap: 12px;
          font-weight: 500;
          color: #303133;
          margin-top: -110px;
          border-top: 1px solid #ebeef5;


          .code-result-image {
            width: 24px;
            height: 24px;
            animation: pulse 1.5s infinite;
          }
        }

        .group_15 {
          z-index: 13;
          overflow: visible; // 修改溢出设置
          display: flex;
          flex-direction: column;
          // height: calc(100% - 70px); // ✅ 新增高度计算
          overflow-y: auto; // ✅ 修改为auto
          padding: 20px;
          width: 100%;
          box-sizing: border-box;
          // margin-top: 15px;
          // margin-left: 44px;

          .section_3 {
            width: 100%;
          }

          .status-tip {
            background: #f0f4ff;
            padding: 12px;
            border-radius: 8px;
            color: #409eff;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            flex-shrink: 0; // 防止被压缩
            margin-bottom: 16px;

            &::before {
              content: "💡";
              font-size: 18px;
            }
          }

          .text_1 {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 16px;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;

            &.success {
              background: #e1f3d8;
              color: #67c23a;

              &::before {
                content: "✅";
              }
            }

            &.warning {
              background: #fdf6ec;
              color: #e6a23c;

              &::before {
                content: "⚠️";
              }
            }

            &.red {
              background: #fef0f0;
              color: #f56c6c;

              &::before {
                content: "❌";
              }
            }

            &.info {
              background: #f0f4ff;
              color: #409eff;

              &::before {
                content: "⏳";
              }
            }
          }

          .error-text {
            background: #f6f8fa;
            
            padding: 12px;
            border-radius: 8px;
            color: #f56c6c;
            font-size: 13px;
            line-height: 1.6;
            border-left: 3px solid #f56c6c;
          }
        }
      }
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.1);
  }

  100% {
    transform: scale(1);
  }
}

/* 按钮美化 */
.el-button {
  transition: all 0.3s;
  border-radius: 8px;
  font-weight: 500;
  letter-spacing: 0.5px;

  &.is-plain {
    border-width: 1px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
  }

  &--primary.is-plain {
    background: linear-gradient(45deg, #409eff, #79bbff);
    color: white;
    border: none;

    &:hover {
      opacity: 0.9;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    }
  }

  &--warning.is-plain {
    background: linear-gradient(45deg, #e6a23c, #f3d19e);
    color: white;
    border: none;

    &:hover {
      opacity: 0.9;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
    }
  }
}

/* 表格美化 */
:deep(.el-table) {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

  th {
    background: #f6f8fa !important;
    font-weight: 600;
    color: #2c3e50;
  }

  td {
    font-family: Monaco, Consolas, monospace;
    font-size: 13px;
    padding: 12px 0;
  }

  tr:hover td {
    background: #f8fafc !important;
  }
}

/* 对话框穿透样式 */
:deep(.el-dialog) {
  border-radius: 12px !important;

  .el-dialog__header {
    background: #f6f8fa;
    border-radius: 12px 12px 0 0;
    padding: 16px 24px;
    margin-right: 0;

    .el-dialog__title {
      color: #2c3e50;
      font-weight: 600;
    }
  }

  .el-dialog__footer {
    padding: 16px 24px;
    background: #f6f8fa;
    border-radius: 0 0 12px 12px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

.submit-confirm-list {
  margin: 15px 0 0 20px;
  padding: 0;
  color: #606266;
  line-height: 1.8;
  font-size: 14px;

  li {
    list-style-type: none;
    position: relative;
    padding-left: 25px;
    margin-bottom: 8px;

    &::before {
      content: "✔️";
      position: absolute;
      left: 0;
      top: 2px;
      color: #67C23A;
    }
  }
}
</style>